package com.tianchi.lexiang.background;

import java.io.IOException;

import com.tianchi.lexiang.R;
import com.tianchi.lexiang.background.adapter.StaticWallpaperImageAdapter;

import android.app.Activity;
import android.app.WallpaperManager;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;

public class StaticWallpaperSetting extends Activity implements OnClickListener, OnItemSelectedListener {
	
	private ImageView wallpaperView;
	
	private Gallery wallpaperGallery;
	
	private Button wallpaperSet;
	private Button back;
	
	private WallpaperManager wallManager;
	private Integer imageId ;
	
	 @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.static_wallpaper_setting);
		initView();
	}
	 
	private  void initView(){
		wallpaperView = (ImageView)findViewById(R.id.wallpaper_view);
		
		StaticWallpaperImageAdapter adapter = new StaticWallpaperImageAdapter(this);  
		TypedArray typedArray = obtainStyledAttributes(R.styleable.Gallery);   
		adapter.setmGalleryItemBackground(typedArray.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0));   

		wallpaperGallery = (Gallery)findViewById(R.id.wallpaper_gallery);
		wallpaperGallery.setAdapter(adapter);
		wallpaperGallery.setOnItemSelectedListener(this);
		
		
		
		wallpaperSet = (Button)findViewById(R.id.set);
		wallpaperSet.setOnClickListener(this);
		
		back = (Button)findViewById(R.id.back);
		back.setOnClickListener(this);
		
		imageId = StaticWallpaperImageAdapter.imagesArr[0];
		wallpaperView.setImageResource(imageId);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.back:
			StaticWallpaperSetting.this.finish();
			break;
		case R.id.set:
			 wallManager = (WallpaperManager) getSystemService(WALLPAPER_SERVICE);
			 try {
				wallManager.setResource(imageId);
				Toast.makeText(StaticWallpaperSetting.this, getString(R.string.wallpaper_setting_success), Toast.LENGTH_SHORT);
				StaticWallpaperSetting.this.finish();
				Toast.makeText(StaticWallpaperSetting.this, getString(R.string.wallpaper_setting_success), Toast.LENGTH_SHORT);
			} catch (IOException e) {
				Toast.makeText(StaticWallpaperSetting.this, getString(R.string.wallpaper_setting_failure), Toast.LENGTH_SHORT);
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		imageId = StaticWallpaperImageAdapter.imagesArr[position];
		wallpaperView.setImageResource(imageId);
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		
	}
}
